package com.twinkle.dbmanage.ui;

import com.twinkle.dbmanage.vo.DBConfig;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author Twinkle
 */
public class ConfigFrame extends JFrame {
    private static final int WINDOW_WIDTH = 400;
    private static final int WINDOW_HEIGHT = 300;

    private static final String CONN_STR = "jdbc:mysql://localhost:3306/homework1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&nullCatalogMeansCurrent=true";
    private static final String CONN_USERNAME = "root";
    private static final String CONN_PASSWORD = "20000628";

    private JPanel p1, p2, p3, p4;
    private JLabel jlb1, jlb2, jlb3;
    private JTextField jtf1, jtf2, jtf3;
    private JButton btn;

    public ConfigFrame() {
        initComponent();
        addComponent();
        addListener();
        initWindows();
    }

    private void initComponent() {
        btn = new JButton("连接");
        jlb1 = new JLabel("URL:");
        jlb2 = new JLabel("用户:");
        jlb3 = new JLabel("密码:");
        jtf1 = new JTextField(20);
        jtf1.setText(CONN_STR);
        jtf2 = new JTextField(20);
        jtf2.setText(CONN_USERNAME);
        jtf3 = new JTextField(20);
        jtf3.setText(CONN_PASSWORD);
        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        p4 = new JPanel();
    }

    private void addComponent() {
        p1.add(jlb1);
        p1.add(jtf1);
        p2.add(jlb2);
        p2.add(jtf2);
        p3.add(jlb3);
        p3.add(jtf3);
        p4.add(btn);
        this.setLayout(new GridLayout(4, 1));
        this.add(p1);
        this.add(p2);
        this.add(p3);
        this.add(p4);
    }

    private void addListener() {
        btn.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        DBConfig config = new DBConfig();
                        config.setUrl(jtf1.getText());
                        config.setUsername(jtf2.getText());
                        config.setPassword(jtf3.getText());
                        ConfigFrame.this.dispose();
                        new MainFrame(config);
                    }
                }
        );

    }

    private void initWindows() {
        this.setTitle("DatabaseManager-Config");
        this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}
